/**
 * 一起学 mapbox !
 *
 * 课程7
 * 创建 popup 地图气泡
 *
 */

mapboxgl.accessToken = 'pk.eyJ1IjoiNGgzajgiLCJhIjoiY202cTRneXdpMDlheDJpb21rdGs2M3V6cSJ9.Ifg4pD0p8LxYmxmxwoTBNA';

const map = (window.map = new mapboxgl.Map({
  container: 'map',
  center: [121.74380266722233, 31.097567372835357],
  zoom: 10,
  style: 'mapbox://styles/mapbox/standard',
  minZoom: 0,
  maxZoom: 21
}));

const creatMaskLayer = () => {
  let bboxRect = [
    [67.02449892481263, 46.12068205599684],
    [129.27494800193972, 53.818622531724515],
    [148.20607666881108, 44.36176722445572],
    [116.95015063975069, 21.070758514708956],
    [89.49824939992271, 21.39242303693443],
    [69.59176292732047, 32.966666928462956],

  ]
  let shangHaiRect = [
    [120.94873075051282, 31.917359573696487],
    [120.62387816073135, 31.480211129450993],
    [120.71006354169259, 30.92165048886433],
    [121.10121278741622, 30.528440625775843],
    [121.79732527076209, 30.611187115841872],
    [122.0790851700641, 30.972823195634035],
    [122.16527055102773, 31.23961239818803],
    [122.16527055102773, 31.60169090734557],
    [121.939862631587, 31.928613523008437],
  ]
  // 基础面数据
  var polygonData = {
    'type': 'FeatureCollection',
    'features': [
      {
        'type': 'Feature',
        'geometry': {
          'type': 'Polygon',
          'coordinates': [
            bboxRect,
            shangHaiRect
          ]
        },
        'properties': {
          fillColor: '#000',
          fillOpacity: 1
        }
      },
    ]
  }

// 3 创建数据源并添加
  var polygonSource = {
    type: 'geojson',
    data: {
      type: "FeatureCollection",
      features: []
    },
  }
  map.addSource('polygonSource', polygonSource)
  var polygon_Source = map.getSource('polygonSource');
  polygon_Source.setData(polygonData)


// 4 创建图层并添加
  var polygonLayer = {
    id: 'polygonLayer',
    type: 'fill',
    source: 'polygonSource',
    layout: {},
    // 特殊化定制 https://docs.mapbox.com/style-spec/reference/layers/#fill
    'paint': {
      'fill-color': ['get', 'fillColor'],
      'fill-opacity': ['get', 'fillOpacity'],
    }
  }
  window.polygonLayer = polygonLayer
  map.addLayer(polygonLayer)


}



const main = () => {
  creatMaskLayer()
}


map.on('click', ev => {
  console.log([ev.lngLat.lng, ev.lngLat.lat])
  // let lon = ev.lngLat.lng
  // let lat = ev.lngLat.lat
  //
  // createPopup([lon, lat])
})

map.on('load', () => {
  main()
})
